package com.example.mycomposelesson.util

import android.util.Log
import ch.qos.logback.classic.LoggerContext
import ch.qos.logback.classic.joran.JoranConfigurator
import mu.KotlinLogging
import org.slf4j.LoggerFactory
import java.io.ByteArrayInputStream

object LogUtil {
    private  val LOGCONFIG="""
        <configuration>
    <property name="LOG_HOME" value="/sdcard/kcrx/logs/" />
    <appender name="logcat" class="ch.qos.logback.classic.android.LogcatAppender">
        <tagEncoder>
            <pattern>kcrxlog</pattern>
        </tagEncoder>
        <encoder>
            <pattern>[%logger{12}]-[%thread]-%msg</pattern>
        </encoder>
    </appender>

    <!-- 按照每天生成日志文件 -->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件输出的文件名-->
            <FileNamePattern>/sdcard/kcrx/logs/%d{yyyy-MM-dd}.log</FileNamePattern>
            <!--日志文件保留天数-->
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出：%d表示日期，%thread表示线程名，%-5level：级别从左显示5个字符宽度%msg：日志消息，%n是换行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{12} - %msg%n</pattern>
            <charset>UTF-8</charset>
        </encoder>
        <!--日志文件最大的大小-->
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>10MB</MaxFileSize>
        </triggeringPolicy>
    </appender>

    <root level="Debug">
        <appender-ref ref="logcat" />
        <appender-ref ref="FILE"/>
    </root>
</configuration>
    """
    val logger=KotlinLogging.logger { "MainLog" }
    fun configLog(){
        val  lc= LoggerFactory.getILoggerFactory() as LoggerContext
        lc.stop()
        val config= JoranConfigurator()
        config.context=lc
        try{
            Log.e("loginit","正在初始化日志配置!")
            config.doConfigure(ByteArrayInputStream(LOGCONFIG.toByteArray()))
        }catch (e:Exception){
            Log.e("loginit","初始化日志配置失败！",e)
            e.printStackTrace()
        }
    }
}